<?php

namespace app\modules\clinical\controllers;

use Yii;
use app\modules\clinical\models\Patient;
use app\models\Helpers;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\AccessControl;
use yii\data\ActiveDataProvider;

/**
 * PatientInfoController implements the CRUD actions for Patient model.
 */
class RelativeController extends Controller
{
    public $enableCsrfValidation = false;

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ]
        ];
    }
    
    /**
     * Lists all Patient models.
     * @return mixed
     */
    public function actionIndex()
    {
        $pt_id = Yii::$app->session->get('pt_id');
        $relation = Patient::findOne($pt_id)->getRelations();

        $dataProvider = new ActiveDataProvider([
            'query' => Patient::find()->where(['in', 'pk_id', array_keys($relation)])
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'rel' => $relation,
        ]);
    }

    public function actionView()
    {
        $id = Yii::$app->request->get('id', false);
        if ($id) {
            return $this->render('/patient/view', [
                'model' => Patient::findOne($id),
                'from' => 'rel',
            ]);
        }
    }

    public function actionCreate()
    {
        $model = new Patient();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $patient = Patient::findOne(Yii::$app->session->get('pt_id'));

            $json = json_decode($patient->pt_rel);
            $add = new \stdClass();
            $add->pt_id = $model->pk_id;
            $add->rel = Yii::$app->request->post('pt_rel');
            $json[] = $add;

            $patient->pt_rel = json_encode($json);
            $patient->save();
			return $this->redirect('index');
        }

        return $this->render('create', [
            'model' => $model,
            'relatives' => Helpers::getEnumValues('hspt_relation', 'relation_type'),
        ]);
    }

    public function actionDelete($id)
    {
        $patient = Patient::findOne(Yii::$app->session->get('pt_id'));
        $json = json_decode($patient->pt_rel);

        foreach ($json as $key => $rel) {
            if ($rel->pt_id == $id) {
                unset($json[$key]);
                break;
            }
        }

        $json = array_values($json);
        $patient->pt_rel = json_encode($json);
        $patient->save();

        $model = Patient::findOne($id);
        $model->delete_at = strtotime(date("Y-m-d H:i:s"));
        $model->save();

        return $this->redirect('/clinical/relative');
    }
}
